<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace backend\controllers;

use builder\helper\H5;
use builder\helper\T;
use common\helper\App;
use common\models\AppLogs;
use common\models\AppLogsService;
use common\models\Tlog;
use Yii;
use builder\base\BaseController;
use common\models\Admin;
use yii\base\DynamicModel;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\Response;

/**
 *
 * @author cleverstone
 * @since ym2.0
 */
class HomeController extends BaseController
{
    public $actionVerbs = [
        'index' => ['GET'],
        '_app_log' => ['GET'],
        '_t_log' => ['GET'],
        '_user_incr_statistics' => ['GET'],
        '_order_incr_statistics' => ['GET'],
        '_app_log_detail' => ['GET'],
        'account' => ['GET', 'POST'],
        'preference' => ['GET', 'POST'],
    ];
    public $undetectedActions = [
        'index',
        '_app_log',
        '_t_log',
        '_user_incr_statistics',
        '_order_incr_statistics',
        '_app_log_detail',
        'account',
        'preference',
    ];

    /**
     * 面板概览
     * @return string|\yii\web\Response
     */
    public function actionIndex()
    {
        //return $this->homePageWithDynamic();
        return $this->homePageWithStatic();
    }

    /**
     * 动态首页
     * @return string|Response
     */
    protected function homePageWithDynamic()
    {
        if ($this->isAjax) {
            //总用户
            ['totalCount' => $totalUserCount, 'normalCount' => $normalUserCount, 'abnormalCount' => $abnormalUserCount, 'newUserCount' => $newUserCount] = ['totalCount' => 900000, 'normalCount' => 850000, 'abnormalCount' => 50000, 'newUserCount' => 50000];
            //总收入
            ['totalAmount' => $totalAmount, 'todayAmount' => $todayAmount] = ['totalAmount' => 500000000, 'todayAmount' => 3000000];
            //总订单
            ['orderCount' => $orderCount, 'orderWaitPayCount' => $orderWaitPayCount, 'orderWaitPostCount' => $orderWaitPostCount, 'orderWaitUseCount' => $orderWaitUseCount] = ['orderCount' => 900000000, 'orderWaitPayCount' => 50000, 'orderWaitPostCount' => 50000, 'orderWaitUseCount' => 50000];
            //售后订单
            ['aftermarketCount' => $aftermarketCount, 'aftermarketApplyingCount' => $aftermarketApplyingCount, 'aftermarketWaitReceiveCount' => $aftermarketWaitReceiveCount,] = ['aftermarketCount' => 50000, 'aftermarketApplyingCount' => 5000, 'aftermarketWaitReceiveCount' => 3000,];

            return $this->asJson(compact('totalUserCount', 'normalUserCount', 'abnormalUserCount', 'newUserCount', 'totalAmount', 'todayAmount', 'orderCount', 'orderWaitPayCount', 'orderWaitPostCount', 'orderWaitUseCount', 'aftermarketCount', 'aftermarketApplyingCount', 'aftermarketWaitReceiveCount'));
        } else {
            App::setViewBreadcrumb([['name' => '首页'], ['name' => '面板概览', 'url' => 'home/index']]);
            return $this->render('index');
        }
    }

    /**
     * 静态首页
     * @return string|Response
     */
    protected function homePageWithStatic()
    {
        App::setViewBreadcrumb([['name' => '首页'], ['name' => '欢迎页', 'url' => 'home/index']]);
        return $this->render('welcome');
    }

    /**
     * 今日应用 异常日志
     * @return \yii\web\Response
     */
    public function action_app_log(): Response
    {
        $startDate = T::dayToAbsoluteDate(-1, false, true);
        $endDate = date('Y-m-d 23:59:59');
        $appLog = AppLogsService::getAppLogsByInterval($startDate, $endDate);

        return $this->asJson(compact('appLog'));
    }

    /**
     * 今日操作日志
     * @return \yii\web\Response
     */
    public function action_t_log(): Response
    {
        $startDate = T::dayToAbsoluteDate(-1, false, true);
        $endDate = date('Y-m-d 23:59:59');
        /** @var Admin $adminUser */
        $adminUser = $this->user->identity;
        $adminID = $adminUser->group == Admin::ADMIN_GROUP ? null : $adminUser->id;
        $tlog= Tlog::getTLogByDateInterval($startDate, $endDate, $adminID);

        return $this->asJson(compact('tlog'));
    }

    /**
     * 用户日增统计
     * @param int $days 天数
     * @return \yii\web\Response
     * - time 用于时间展示
     * - date 用于日期分组
     * - count 用户数量
     */
    public function action_user_incr_statistics($days)
    {
        $data = [];
        if ($days == 30) {
            for ($i = 29; $i >= 0; $i--) {
                $timestamp = strtotime("-{$i} days");
                $date = date('Y-m-d', $timestamp);
                $time = date('m/d', $timestamp);
                $data[] = ['time' => $time, 'date' => $date, 'count' => mt_rand(0, 100000)];
            }
        } else {
            $curDate = date('Y-m-d');
            for ($i = 0; $i < 24; $i++) {
                $time = $i < 10 ? "0$i:00" : $i . ':00';
                $data[] = ['time' => $time, 'date' => $curDate . ' ' . $time, 'count' => mt_rand(0, 5000)];
            }
        }
        return $this->asJson($data);
    }

    /**
     * 订单日增统计
     * @param int|string $days 天数
     * @return \yii\web\Response
     * - date 用于日期分组
     * - count 订单数量
     * - [order_status] 用于订单状态分组
     */
    public function action_order_incr_statistics($days)
    {
        $data = [];
        if (substr($days, 0, 1) == 'g') {
            $days = substr($days, 1);
            $orderStatusCollection = ['待支付', '待发货', '待收货', '已完成'];
            //分组
            if ($days == 30) {
                //30日
                for ($i = 29; $i >= 0; $i--) {
                    $data[] = ['date' => date('Y-m-d', strtotime("-{$i} days")), 'count' => mt_rand(0, 100000), 'order_status' => $orderStatusCollection[array_rand($orderStatusCollection)]];
                }
            } else {
                //当日
                $curDate = date('Y-m-d');
                for ($i = 0; $i < 24; $i++) {
                    $time = $i < 10 ? "0$i:00" : $i . ':00';
                    $data[] = ['date' => $curDate . ' ' . $time, 'count' => mt_rand(0, 5000), 'order_status' => $orderStatusCollection[array_rand($orderStatusCollection)]];
                }
            }
        } else {
            if ($days == 30) {
                //30日
                for ($i = 29; $i >= 0; $i--) {
                    $data[] = ['date' => date('Y-m-d', strtotime("-{$i} days")), 'count' => mt_rand(0, 100000)];
                }
            } else {
                //当日
                $curDate = date('Y-m-d');
                for ($i = 0; $i < 24; $i++) {
                    $time = $i < 10 ? "0$i:00" : $i . ':00';
                    $data[] = ['date' => $curDate . ' ' . $time, 'count' => mt_rand(0, 5000)];
                }
            }
        }

        return $this->asJson($data);
    }

    /**
     * 查看日志详情
     * @param int $id 应用日志表ID
     * @return \yii\web\Response
     */
    public function action_app_log_detail($id)
    {
        $adminUser = $this->user->identity;/** @var Admin $adminUser */
        $appLog = AppLogs::findOneThrowEmptyException($id);/** @var AppLogs $appLog */
        if ($adminUser->group == Admin::ADMIN_GROUP) {
            return $this->asJson($appLog->message);
        } else {
            return $this->asJson('仅系统拥有者可查看，您没有查看权限。');
        }
    }

    /**
     * 账户设置
     * @return \yii\web\Response|string
     * @throws \Throwable
     */
    public function actionAccount()
    {
        /** @var Admin $user */
        $user = $this->user->identity;
        if ($this->isPost) {
            $bodyParams = $this->filteredPost;
            $bodyParams['photo'] = App::getFileLinkFromParams($bodyParams, 'photo');

            $oldPassword = $user->password_hash;
            $user->password_hash = '';

            $user->setScenario('SCE_Account_Setting');
            $user->load($bodyParams);
            if (!$user->validate()) {
                return $this->asFail($user->error);
            }

            if ($user->password_hash) {
                $user->setPassword($user->password_hash);
            } else {
                $user->password_hash = $oldPassword;
            }

            $user->save(false);

            return $this->asOk('账号【'.$user->username.'】编辑成功。');

        } else {
            App::setViewBreadcrumb([
                ['name' => '首页', 'url' => 'home/index'],
                ['name' => '账户设置', 'url' => 'home/account'],
            ]);

            $relativeCreated = Yii::$app->formatter->asRelativeTime(strtotime($user->created_at));
            $relativeUpdated = Yii::$app->formatter->asRelativeTime(strtotime($user->updated_at));

            $viewBuilder = $this->viewBuilder;
            $form = $viewBuilder->form;
            $form->setId('Home_Account')
                ->setTitle('账户设置')
                ->setGroup('账户设置', 'account_setting')
                ->setGroupCol(6)
                ->setFooterLayout(['class' => 'col-md-6'])
                ->setFooterFixed(false)
                ->setFormControl([
                    'photo' => $this->formControl->file()->label('头像')->scenarioImage()->max(1)->defaultValue($user->photo),
                    'password_hash' => $this->formControl->password()->label('密码'),
                    'password_hash_repeat' => $this->formControl->password()->label('重复密码'),
                    'email' => $this->formControl->text()->label('邮箱')->checkRule(JS_EMAIL_REGEX)->required()->defaultValue($user->email)->comment(empty($user->email) ? H5::text('★请完善邮箱★', ['class' => 'layui-font-red']) : ''),
                    'mobile' => $this->formControl->text()->label('手机号码')->checkRule(JS_MOBILE_REGEX)->maxLength(11)->required()->defaultValue($user->mobile)->comment(empty($user->mobile) ? H5::text('★请完善手机号★', ['class' => 'layui-font-red']) : ''),
                    'created_at' => $this->formControl->staticText()->label('注册时间')->defaultValue($user->created_at . H5::text(" ($relativeCreated) ", ['class' => 'layui-font-red'], 'strong')),
                    'updated_at' => $this->formControl->staticText()->label('上次更新时间')->defaultValue($user->updated_at . H5::text(" ($relativeUpdated) ", ['class' => 'layui-font-red'], 'strong')),
                ])
                ->setSubmitConfirm()
                ->setResetBtn()
                ->setSubmitBtn('保存设置');

            return $viewBuilder->render();
        }
    }

    /**
     * 用户偏好设置
     * @return string|void|\yii\web\Response
     * @throws \builder\base\InvalidInstanceException
     * @throws \builder\base\NotFoundParamsException
     * @throws \yii\base\InvalidConfigException
     */
    public function actionPreference()
    {
        $viewThemeKeys = [];
        $viewThemeMap = [];
        foreach (App::params('admin.viewTheme', []) as $value) {
            $comp = $value['key'] . '|' . $value['primaryColor'];
            $label = Html::tag('span', '', [
                    'class' => 'layui-badge layui-badge-dot',
                    'style' => [
                        'background-color' => $value['primaryColor'],
                        'width' => '10px',
                        'height' => '10px',
                    ],
                ]) . "\n" . $value['name'];
            $viewThemeKeys[] = $comp;
            $viewThemeMap[$comp] = $label;
        }
        $viewThemeKeys[] = 'flowSystem';
        $viewThemeMap['flowSystem'] = '跟随系统';

        /** @var Admin $user */
        $user = $this->user->identity;
        $preference = !empty($user->user_preference) ? Json::decode($user->user_preference) : [];
        $userViewTheme = !empty($preference['view_theme']) ? $preference['view_theme'] : [];

        if ($this->isPost) {
            $bodyParams = $this->post;
            $dynamicModel = DynamicModel::validateData($bodyParams, [
                [['uiPrimary', 'asideExpanded', 'menuLayout'], 'required'],
                [['uiPrimary'], 'in', 'range' => $viewThemeKeys],
                [['asideExpanded'], 'in', 'range' => [0, 1]],
                [['menuLayout'], 'in', 'range' => ['list', 'grid']],
            ]);
            if ($dynamicModel->hasErrors()) {
                return $this->asFail(current($dynamicModel->firstErrors));
            }

            if ($dynamicModel->uiPrimary != 'flowSystem') {
                $map = explode('|', $dynamicModel->uiPrimary);
                $userViewTheme['uiTheme'] = $map[0];
                $userViewTheme['themeColor'] = $map[1];
            } else {
                unset($userViewTheme['uiTheme'], $userViewTheme['themeColor']);
            }

            $userViewTheme['asideExpanded'] = !!$dynamicModel->asideExpanded;
            $userViewTheme['menuLayout'] = $dynamicModel->menuLayout;
            $preference['view_theme'] = $userViewTheme;
            $user->user_preference = Json::encode($preference);
            $user->save(false);

            return $this->asOk(null);
        } else {
            $defaultUiPrimary = !empty($userViewTheme['uiTheme']) && !empty($userViewTheme['themeColor']) ? ($userViewTheme['uiTheme'] . '|' . $userViewTheme['themeColor']) : 'flowSystem';
            $defaultAsideExpanded = $userViewTheme['asideExpanded'] ?? ($this->view->params['asideExpanded'] ?? false);
            $defaultMenuLayout = $userViewTheme['menuLayout'] ?? ($this->view->params['menuLayout'] ?? 'grid');

            App::setViewBreadcrumb([
                ['name' => '首页', 'url' => 'home/index'],
                ['name' => '偏好设置', 'url' => 'home/preference'],
            ]);

            $viewBuilder = $this->viewBuilder->setPartial();
            $form = $viewBuilder->form;
            $form->setId('Home_Preference')
                ->setRootLayout([
                    'class' => 'h-100',
                ])
                ->setTitle('偏好设置')
                ->setFormControl([
                    'uiPrimary' => $this->formControl->radio()->label('主题颜色：')->options($viewThemeMap)->labelIsHtml()->defaultValue($defaultUiPrimary)->required(),
                    'asideExpanded' => $this->formControl->radio()->label('菜单折叠：')->options(['关闭', '展开'])->defaultValue((int)$defaultAsideExpanded)->required(),
                    'menuLayout' => $this->formControl->radio()->label('菜单布局：')->options(['grid' => '网格', 'list' => '列表'])->defaultValue($defaultMenuLayout)->required(),
                ])
                ->setSubmitBtn('保存设置')
                ->setAutoClose()
                ->setSubmittedCalls([
                    'parent' => ['_preference_reload'], // 自定义回调。
                ]);

            return $viewBuilder->render();
        }
    }
}